<!DOCTYPE html>
<html>
<head>
    <title>学生登录</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .info-form {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin: 20px auto;
            max-width: 500px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
        }
        .form-group select, .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        .submit-btn {
            display: block;
            width: 100%;
            padding: 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
        }
        .submit-btn:hover {
            background-color: #45a049;
        }
        .waiting-page {
            display: none;
            text-align: center;
            padding: 40px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .waiting-page h2 {
            color: #333;
            margin-bottom: 20px;
        }
        .waiting-page p {
            color: #666;
            font-size: 18px;
            margin: 10px 0;
        }
        .student-count {
            font-size: 24px;
            color: #4CAF50;
            font-weight: bold;
        }
        .question-panel {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80%;
            max-width: 600px;  /* 减小最大宽度 */
            max-height: 80vh;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            overflow-y: auto;
            z-index: 1000;
        }
        
        .question-item {
            margin-bottom: 20px;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .question-content p {
            margin: 5px 0;
            font-size: 16px;
            font-weight: bold;
        }
        
        .options-list {
            display: flex;
            flex-direction: row;
            justify-content: center;
            gap: 20px;  /* 稍微增加选项间距 */
            margin: 10px 0;
        }
        
        .option-item {
            flex: 0 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100px;  /* 增加宽度到100px */
            height: 45px;  /* 稍微增加高度 */
            padding: 0;
            background-color: #f5f5f5;
            border: 2px solid transparent;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .option-item:hover {
            background-color: #e8e8e8;
        }
        
        .option-item input[type="radio"] {
            display: none;
        }
        
        .option-item.selected {
            background-color: #e6f7ff;
            border-color: #1890ff;
        }
        
        .option-item label {
            cursor: pointer;
            font-size: 18px;  /* 稍微增大字体 */
            font-weight: bold;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .submit-answer-btn {
            width: 100%;
            padding: 12px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 20px;
        }
        
        .submit-answer-btn:disabled {
            background-color: #d9d9d9;
            cursor: not-allowed;
        }
        
        .submit-answer-btn:not(:disabled):hover {
            background-color: #40a9ff;
        }
        
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        .close-btn {
            position: absolute;
            right: 10px;
            top: 10px;
            font-size: 24px;
            background: none;
            border: none;
            cursor: pointer;
            color: #999;
        }

        .close-btn:hover {
            color: #666;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>登录成功！</h1>
    </div>

    <!-- 学生信息表单 -->
    <div class="info-form" id="studentInfo">
        <div class="form-group">
            <label for="group">小组：</label>
            <select id="group" required>
                <option value="">请选择小组...</option>
                <script>
                    for(let i = 1; i <= 8; i++) {
                        document.write(`<option value="group${i}">第${i}组</option>`);
                    }
                </script>
            </select>
        </div>
        <div class="form-group">
            <label for="name">姓名：</label>
            <input type="text" id="name" required placeholder="请输入你的姓名">
        </div>
        <button class="submit-btn" onclick="submitStudentInfo()">提交</button>
    </div>

    <!-- 等待页面 -->
    <div class="waiting-page" id="waitingPage">
        
        
        <p id="studentConfirmInfo"></p>
        <p>当前已登录学生人数：<span class="student-count" id="studentCount">0</span></p>
        <p>请不要关闭此页面，等待教师开始上课。</p>
        <button onclick="logout()" style="
            margin-top: 20px;
            padding: 8px 16px;
            background-color: #ff4d4f;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        ">信息有误，重新登录</button>
    </div>

    <div class="overlay" id="overlay"></div>

    <div class="question-panel" id="questionPanel">
        <button class="close-btn" onclick="closeQuestionPanel()">×</button>
        <div id="questionsContainer">
            <!-- 题目将在这里动态生成 -->
        </div>
        <button 
            id="submitAnswerBtn" 
            class="submit-answer-btn" 
            onclick="submitAnswers()" 
            disabled
        >
            提交答案
        </button>
    </div>

    <script>
        let currentQuestions = [];  // 当前题目
        let answeredQuestionIds = new Set();  // 已回答的题目ID集合
        let studentInfo = JSON.parse(localStorage.getItem('studentInfo')) || null;

        // 页面加载时检查是否已有保存的学生信息
        window.onload = function() {
            // 初始化时隐藏问题面板和遮罩层
            document.getElementById('questionPanel').style.display = 'none';
            document.getElementById('overlay').style.display = 'none';

            if (studentInfo) {
                // 如果有保存的学生信息，直接显示等待页面
                document.getElementById('studentInfo').style.display = 'none';
                document.getElementById('waitingPage').style.display = 'block';
                document.getElementById('studentConfirmInfo').textContent = 
                    `${studentInfo.group_id.replace('group', '第')}组 - ${studentInfo.name}`;
                
                // 开始定期更新学生人数
                updateStudentCount();
                setInterval(updateStudentCount, 5000);

                // 开始定期检查新题目
                setInterval(checkForNewQuestion, 5000);
            } else {
                // 如果没有学生信息，显示登录表单
                document.getElementById('studentInfo').style.display = 'block';
                document.getElementById('waitingPage').style.display = 'none';
            }
        };

        async function checkForNewQuestion() {
            try {
                const response = await fetch('/api/questions/active');
                const questions = await response.json();
                
                // 检查是否有活动题目
                if (questions && questions.length > 0) {
                    // 获取当前学生的答题情况
                    const answersPromises = questions.map(q => 
                        fetch(`/api/answers/${q.id}`).then(res => res.json())
                    );
                    
                    const allAnswers = await Promise.all(answersPromises);
                    
                    // 过滤出未回答的题目
                    const unansweredQuestions = questions.filter((q, index) => {
                        const questionAnswers = allAnswers[index];
                        // 检查当前学生是否已经回答过这道题
                        const hasAnswered = questionAnswers.some(ans => 
                            ans.name === studentInfo.name && 
                            ans.group_id === studentInfo.group_id
                        );
                        return !hasAnswered;
                    });

                    // 如果有未答题目且问题面板当前未显示，则显示题目
                    if (unansweredQuestions.length > 0) {
                        showQuestion(unansweredQuestions);
                    }
                }
            } catch (error) {
                console.error('检查新题目失败:', error);
            }
        }

        function showQuestion(questions) {
            const panel = document.getElementById('questionPanel');
            const overlay = document.getElementById('overlay');
            const container = document.getElementById('questionsContainer');
            const submitBtn = document.getElementById('submitAnswerBtn');
            
            // 只有当面板未显示且有未答题目时才显示
            if (panel.style.display !== 'block' && questions && questions.length > 0) {
                currentQuestions = questions;
                panel.style.display = 'block';
                overlay.style.display = 'block';
                
                // 清空容器
                container.innerHTML = `<h3>共${questions.length}道题目</h3>`;
                
                // 生成所有题目
                questions.forEach((question, index) => {
                    const questionDiv = document.createElement('div');
                    questionDiv.className = 'question-item';
                    questionDiv.innerHTML = `
                        <div class="question-content">
                            <p>第${index + 1}题</p>
                            <div class="options-list">
                                <div class="option-item" onclick="selectOption(this, ${question.id}, 'A')">
                                    <input type="radio" 
                                        name="question${question.id}" 
                                        value="A" 
                                        id="question${question.id}_A"
                                    >
                                    <label for="question${question.id}_A">A</label>
                                </div>
                                <div class="option-item" onclick="selectOption(this, ${question.id}, 'B')">
                                    <input type="radio" 
                                        name="question${question.id}" 
                                        value="B" 
                                        id="question${question.id}_B"
                                    >
                                    <label for="question${question.id}_B">B</label>
                                </div>
                                <div class="option-item" onclick="selectOption(this, ${question.id}, 'C')">
                                    <input type="radio" 
                                        name="question${question.id}" 
                                        value="C" 
                                        id="question${question.id}_C"
                                    >
                                    <label for="question${question.id}_C">C</label>
                                </div>
                                <div class="option-item" onclick="selectOption(this, ${question.id}, 'D')">
                                    <input type="radio" 
                                        name="question${question.id}" 
                                        value="D" 
                                        id="question${question.id}_D"
                                    >
                                    <label for="question${question.id}_D">D</label>
                                </div>
                            </div>
                        </div>
                    `;
                    container.appendChild(questionDiv);
                });
            }
        }

        // 添加选项选择函数
        function selectOption(element, questionId, value) {
            // 移除同一题目中其他选项的选中状态
            const questionOptions = element.parentElement.querySelectorAll('.option-item');
            questionOptions.forEach(option => option.classList.remove('selected'));
            
            // 添加当前选项的选中状态
            element.classList.add('selected');
            
            // 选中单选按钮
            const radio = element.querySelector('input[type="radio"]');
            radio.checked = true;
            
            // 检查是否所有题目都已答
            checkAllAnswered();
        }

        function checkAllAnswered() {
            const submitBtn = document.getElementById('submitAnswerBtn');
            const allAnswered = currentQuestions.every(question => {
                const radios = document.getElementsByName(`question${question.id}`);
                return Array.from(radios).some(radio => radio.checked);
            });
            submitBtn.disabled = !allAnswered;
        }

        async function submitAnswers() {
            if (!studentInfo || currentQuestions.length === 0) return;

            const submitBtn = document.getElementById('submitAnswerBtn');
            submitBtn.disabled = true;
            submitBtn.textContent = '正在提交...';

            try {
                // 修改答案数据结构
                const answers = currentQuestions.map(question => {
                    const selectedOption = document.querySelector(
                        `input[name="question${question.id}"]:checked`
                    );
                    return {
                        student_name: studentInfo.name,
                        group_id: studentInfo.group_id,
                        question_id: question.id,
                        answer: selectedOption.value  // A, B, C, D
                    };
                });

                // 添加日志以检查发送的数据
                console.log('Submitting answers:', { answers });

                const response = await fetch('/api/answers/batch', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ answers })  // 确保包装在 answers 字段中
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '提交答案失败');
                }

                submitBtn.textContent = '提交成功';
                submitBtn.style.backgroundColor = '#52c41a';
                
                // 记录已回答的题目ID
                currentQuestions.forEach(q => answeredQuestionIds.add(q.id));
                
                // 2秒后关闭弹窗
                setTimeout(() => {
                    closeQuestionPanel();
                }, 2000);
            } catch (error) {
                console.error('提交答案失败:', error);
                alert('提交答案失败，请重试');
                submitBtn.disabled = false;
                submitBtn.textContent = '提交答案';
            }
        }

        async function submitStudentInfo() {
            const group = document.getElementById('group').value;
            const name = document.getElementById('name').value.trim();

            if (!group || !name) {
                alert('请填写完整信息！');
                return;
            }

            // 显示确认对话框
            const confirmMsg = `请确认你的信息：\n小组：${group.replace('group', '第')}组\n姓名：${name}`;
            if (!confirm(confirmMsg)) {
                return;
            }

            try {
                const response = await fetch('/api/students', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: name,
                        group_id: group
                    })
                });

                if (response.ok) {
                    studentInfo = {
                        name: name,
                        group_id: group
                    };
                    
                    // 保存学生信息到 localStorage
                    localStorage.setItem('studentInfo', JSON.stringify(studentInfo));
                    
                    // 切换到等待页面
                    document.getElementById('studentInfo').style.display = 'none';
                    document.getElementById('waitingPage').style.display = 'block';
                    
                    // 显示学生信息
                    document.getElementById('studentConfirmInfo').textContent = 
                        `${group.replace('group', '第')}组 - ${name}`;
                    
                    // 开始定期更新学生人数
                    updateStudentCount();
                    setInterval(updateStudentCount, 5000);

                    // 开始定期检查新题目
                    setInterval(checkForNewQuestion, 5000);
                } else {
                    throw new Error('提交失败');
                }
            } catch (error) {
                console.error('提交学生信息失败:', error);
                alert('提交失败，请重试！');
            }
        }

        async function updateStudentCount() {
            try {
                const response = await fetch('/api/students/count');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                console.log('收到的学生数据:', data);  // 添加调试日志
                
                if (data.count !== undefined) {
                    document.getElementById('studentCount').textContent = data.count;
                } else {
                    console.error('返回的数据中没有 count 字段:', data);
                }
            } catch (error) {
                console.error('获取学生人数失败:', error);
            }
        }

        // 立即调用一次更新
        updateStudentCount();

        // 设置定时更新
        setInterval(updateStudentCount, 5000);

        // 修改退出登录功能
        async function logout() {
            if (!studentInfo) return;
            
            try {
                // 发送请求删除学生信息
                const response = await fetch(`/api/students/${studentInfo.group_id}/${encodeURIComponent(studentInfo.name)}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    // 清除本地存储
                    localStorage.removeItem('studentInfo');
                    studentInfo = null;
                    // 修改这里：直接跳转到首页
                    window.location.href = '/';  // 或者 window.location.href = '/static/index.html';
                } else {
                    throw new Error('退出失败');
                }
            } catch (error) {
                console.error('退出登录失败:', error);
                alert('退出失败，请重试');
                // 即使服务器请求失败，也清除本地存储并跳转到首页
                localStorage.removeItem('studentInfo');
                studentInfo = null;
                window.location.href = '/';  // 或者 window.location.href = '/static/index.html';
            }
        }

        // 修改关闭面板函数
        function closeQuestionPanel() {
            const panel = document.getElementById('questionPanel');
            const overlay = document.getElementById('overlay');
            panel.style.display = 'none';
            overlay.style.display = 'none';
            
            // 清空当前题目，但保留已答题记录
            currentQuestions = [];
        }
    </script>
</body>
</html>